// 为所有请求加上token以及url前缀
import {message, Modal} from 'antd';
import {getIntl, getLocale} from 'umi';


export const authHeaderInterceptor = (url, options) => {
  const token = localStorage.getItem('Authorization');
  const authHeader = {
    Authorization: token ? `${token}` : '',
  };
  return {
    url: `${url}`,
    options: {
      ...options,
      interceptors: true,
      headers: authHeader,
      params: {
        t: new Date().getTime(),
      },
    },
  };
};
const responseInterceptor = async (response) => {
  let result;
  try {
     result = await response.clone().json();
  } catch (e) {
    return response;
  }

  if (result.code !== 200 && !result.data) {
    if (response.status === 404) {
      message.warning(`接口不存在`);
    } else {
      switch (result.code) {
        case 401:
          localStorage.clear();
          message.info('请先登录');
          break;
        case 403:
          message.info(result.msg);
          break;
        case 500:
          message.error(result.msg);
          break;
        default:
          if (result.message !== sessionStorage.getItem('errorMessage')) {
            sessionStorage.setItem('errorMessage', result.message);
            setTimeout(() => {
              sessionStorage.removeItem('errorMessage');
            }, 1500);
            Modal.warning({
              title: '提示 :',
              content: result.message || '接口返回结果异常',
            });
          }
          break;
      }
    }
    return Promise.reject(result);
  }
  return result;

}
export default {
  errorConfig: {},
  errorHandler: (error) => {
    return Promise.reject(error);
  },
  requestInterceptors: [authHeaderInterceptor],
  responseInterceptors: [responseInterceptor]
};

